#include "mainwidget.h"
#include <QApplication>
#include <QMutex>
#include <stdio.h>
#include <stdlib.h>
#include <QTextCodec>
#include "Temperature/tempmain.h"
#include "Temperature/tempcase.h"
#include "inputcontex/myinputpanelcontext.h"
//#include <QMessageLogContext>
#include "globalapp.h"
//#include "pinyin/syszuxpinyin.h"
//#include "pinyin/syszuxim.h"
//#define LOG_ON

#if QT_VERSION > 0x50000
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
#else
void outputMessage(QtMsgType type, const char *msg)
#endif
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug:");
        break;

    case QtWarningMsg:
        text = QString("Warning:");
        break;

    case QtCriticalMsg:
        text = QString("Critical:");
        break;

    case QtFatalMsg:
        text = QString("Fatal:");
    }


    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("(%1)").arg(current_date_time);
#if QT_VERSION > 0x50000
    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
#else
    QString message = QString("%1 %2 %3").arg(text).arg(msg).arg(current_date);
#endif
    QFile file(qApp->applicationDirPath()+"/log.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();

    mutex.unlock();
}

int main(int argc, char *argv[])
{

    GlobalApp a(argc, argv);

    QFile file(qApp->applicationDirPath()+"/log.txt");
    file.open(QIODevice::WriteOnly);
    file.close();
#ifdef LOG_ON
#if QT_VERSION > 0x50000
    qInstallMessageHandler(outputMessage);
#else
    qInstallMsgHandler(outputMessage);
#endif
#endif
    MainWidget w;
    a.setWidows(&w);
#if QT_VERSION > 0x50000
    w.showMaximized();
#else
    w.showMaximized();
    MyInputPanelContext* inputContext = new MyInputPanelContext;
    a.setInputContext(inputContext);
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForLocale(codec);
    QTextCodec::setCodecForCStrings(codec);
    QTextCodec::setCodecForTr(codec);
//    QWSInputMethod* im = new SyszuxIM;
//    QWSServer::setCurrentInputMethod(im);
//    QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312"));
#endif
//    QApplication a(argc, argv);
//    tempW.show();
//    a.setWidows(&tempW);

    return a.exec();
}
